package protocol.data.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;

import protocol.common.entity.JedisParameter;
import protocol.common.util.CJLog;
import protocol.common.util.ConfigLoader;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtil {
	private static Log logger = CJLog.getLogConsole();
	private static boolean initMark = false;
	private static Map<String,JedisPool> poolMap;
	private static JedisPoolConfig jedisPoolConfig;
	private static String defaultKey;
	
	public static  void init(){
		if(!initMark){
			poolMap = new HashMap<String,JedisPool>();
			
			jedisPoolConfig = new JedisPoolConfig();
			jedisPoolConfig.setMaxActive(ConfigLoader.getInt("Redis.Pool.maxActive"));
			jedisPoolConfig.setMaxIdle(ConfigLoader.getInt("Redis.Pool.maxIdle"));
			jedisPoolConfig.setMaxWait(ConfigLoader.getInt("Redis.Pool.maxWait"));
			jedisPoolConfig.setTestOnBorrow(ConfigLoader.getBoolean("Redis.Pool.testOnBorrow"));
			
			String configKey = ConfigLoader.getStr("Redis.Pool");
			String[] keyItems = configKey.split(",");
			defaultKey = keyItems[0];
			for(String key : keyItems){
				JedisPool jedisPool = new JedisPool(jedisPoolConfig, 
								                    ConfigLoader.getStr("Redis."+key+".ip"),
								                    ConfigLoader.getInt("Redis."+key+".port"),
								                    ConfigLoader.getInt("Redis."+key+".timeout"),
								                    ConfigLoader.getStr("Redis."+key+".pass"),
								                    ConfigLoader.getInt("Redis."+key+".database"));
				poolMap.put(key,jedisPool);
			}
			initMark = true;
			logger.info("<系统信息> JedisPool已经初始化完毕");
		}
	}
	
	public static void init(JedisParameter jedisParameter){
		JedisPool jedisPool = new JedisPool(jedisPoolConfig,
								jedisParameter.getHost(),
								jedisParameter.getPort(),
								300,
								jedisParameter.getPassword(),
								jedisParameter.getDatabase());
		poolMap.put(jedisParameter.getConfigId(),jedisPool);
	}
	
	public static Jedis getJedis(String key){
		if(!initMark){
			init();
		}
		return poolMap.get(key).getResource();
	}
	
	public static void returnJedis(Jedis jedis,String key){
		JedisPool jedisPool = poolMap.get(key);
		if(jedis!=null) {
			if(jedis.isConnected()){
				jedisPool.returnResource(jedis);
			}else{
				jedisPool.returnBrokenResource(jedis);
			}
		}
	}
	
	public static Jedis getJedis(){
		return getJedis(defaultKey);
	}
	
	public static void returnJedis(Jedis jedis){
		returnJedis(jedis,defaultKey);
	}
	
	public static JedisPool getJedisPool(){
		return poolMap.get(defaultKey);
	}
	
	public static JedisPool getJedisPool(String key){
		return poolMap.get(key);
	}
}
